const restDao = require("../../dao/rest/RestDao")
const { getType } = require("../../utils")
const { decrypt, encrypt } = require("../../utils/crypto")

module.exports = {
    addService: async (req, res) => {
        return restDao.addDao(req, req.body)
    },
    deleteService: async (req, res) => {
        return restDao.deleteDao(req, req.query)
    },
    updateService: async (req, res) => {
        return restDao.updateDao(req, req.body)
    },
    getService: async (req, res) => {
        const result = await restDao.getDao(req, req.query)
        if (req.Model.modelName === "User" && result && getType(result) === "Object") {
            result.username && (result.username = encrypt(result.username))
            result.password && (result.password = encrypt(result.password))
        }
        return result
    },
    getListService: async (req, res) => {
        const { page = 1, pageSize = 6, condition = {} } = req.query
        const start = (page - 1) * pageSize
        const result = await restDao.getListDao(req, condition, start, pageSize)
        if (req.Model.modelName === "User" && result && getType(result) === "Array" && result.length) {
            return result.map(item => {
                item.username && (item.username = encrypt(item.username))
                item.password && (item.password = encrypt(item.password))
                return item
            })
        }
        if(req.Model.modelName === "Camera" && result && getType(result) === "Array" && result.length) {
            return result.map(item => {
                item.host && (item.host = encrypt(item.host))
                item.username && (item.username = encrypt(item.username))
                item.password && (item.password = encrypt(item.password))
                return item
            })
        }
        return result
    },
    getCountService: async (req, res) => {
        return restDao.getCountDao(req, req.query)
    }
}
